package com.mbigger.wechat.mp.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mbigger.wechat.mp.config.WxMpConfiguration;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/wx/auth/{appid}")
public class WebAuthController {

	/**
	 * 第一步：添加参数，生成授权URL
	 * 
	 * @param appid
	 * @return
	 */

	@GetMapping("/index")
	public String auth(@PathVariable String appid) {
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
		;
		String url = "http://ihk8x7.natappfree.cc/wx/auth/" + appid + "/getUserInfo";
		return wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, "bind");
	}

	/**
	 * 通过返回的CODE，获取access_token，进而获取user_info，需在服务端请求
	 * 
	 * @param appid
	 * @param code
	 * @return
	 */
	@GetMapping("/getUserInfo")
	public String getUserInfo(@PathVariable String appid, @RequestParam String code) {
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
		try {
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
			System.err.println(wxMpOAuth2AccessToken);
			WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			System.err.println(wxMpUser);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return "ok";
	}

}
